import { MapLike } from "../../common/types";
import {
    getMapEntries,
    getObjectArrayMapEntries,
    hasOwnProperty,
    stringIsBoolean,
    stringIsInteger
} from "../../common/util";
import { DiagnosticMessage } from "../diagnostic";
import {
    ArrayDecl,
    ArrayTypeSignature,
    BinaryExpression,
    BinaryOperatorKind,
    Binding,
    Block,
    CallExpr,
    CategoricalItemLiteral,
    CategoricalLiteral,
    ClassSignature,
    ConstantDeclaration,
    DelcareKeywordKind,
    DoStat,
    EnumMemberSignature,
    EnumSignature,
    EventSection,
    EventSectionKind,
    DmsSectionKeywordKind,
    ExprStat,
    ForEachStat,
    ForStat,
    FunctionDeclaration,
    FunctionSignature,
    GlobalSQLVariablesSection,
    IfStat,
    IndexExpr,
    InheritLike,
    InputDataSourceSection,
    InterfaceSignature,
    IterationExpr,
    JobSection,
    JumpStatement,
    KeywordToken,
    KeywordTokenKind,
    LineLocation,
    LocalDecls,
    LoggingSection,
    MemberExpr,
    MDMAreaName,
    MDMCategories,
    MDMCategory,
    MDMCategoryElementType,
    MDMCategoryElementTypeFlags,
    MDMCategoryExpression,
    MDMCellStyle,
    MDMCellStylePropertyFlags,
    MDMClass,
    MDMControlStyle,
    MDMControlStylePropertyFlags,
    MDMDbQuestions,
    MDMDocument,
    MDMField,
    MDMFieldFlags,
    MDMFontStyle,
    MDMFontStylePropertyFlags,
    MDMHierarchicalView,
    MDMKeywordKind,
    MDMLabel,
    MDMLabelTypeFlags,
    MDMMultiplier,
    MDMOther,
    MDMPage,
    MDMProperties,
    MDMProperty,
    MetadataSection,
    MDMStyle,
    MDMPropertyFlags,
    MDMTemplate,
    MDMTemplates,
    MDMUsageType,
    MDMUsageTypeFlags,
    MDMUserContextFlags,
    MissingNodeArray,
    ModuleSignature,
    Node,
    NodeArray,
    ObjectCollectionIterator,
    ObjectType,
    ObjectTypeFlag,
    OutputDataSourceSection,
    ParameterSignature,
    PrecedureCanExit,
    PPDefine,
    PPIfDef,
    PPIf,
    PPInclude,
    PPKeywordKind,
    PPUndef,
    PropertySignature,
    ReadonlySymbolTable,
    ReadonlyTextRange,
    ResumeStatement,
    SectionKind,
    SectionStat,
    SelectCaseClause,
    SelectCaseComparison,
    SelectStat,
    SourceFile,
    Symbol,
    SymbolTable,
    SyntaxKind,
    TextRange,
    Token,
    Type,
    TypeFlag,
    UnaryExpr,
    UnaryOperatorKind,
    VariableDecl,
    WhileStat,
    WithStat,
    RoutingSection,
    TextChangeRange,
    ConstSignature,
    SymbolKind,
    PPIfNDef,
    MDMCodes,
    MDMDeclarationValueLike,
    MDMDeclarationKind,
    TextSpan,
    TextPosition,
    MDMFactor,
    MDMKeycode,
    FileKind,
    CharacterCodes,
} from "./types";

export function forEachChild<T>(node: Node, nodeCallback: (node: Node) => T | undefined, nodeArrayCallback: ((nodeArray: NodeArray<Node>) => T | undefined) | undefined): T | undefined {
    if (!node || (node.kind <= SyntaxKind.identifier && node.kind !== SyntaxKind.sourceFile)) {
        return;
    }

    let result: T | undefined;
    switch (node.kind) {
        // literal
        case SyntaxKind.categoricalItemLiteral:
            return visitNode((node as CategoricalItemLiteral).upper, nodeCallback)
                || visitNode((node as CategoricalItemLiteral).lower, nodeCallback);
        case SyntaxKind.categoricalLiteral:
            return visitNodes((node as CategoricalLiteral).categories, nodeCallback, nodeArrayCallback);
        // Declarations
        case SyntaxKind.localDecls:
            return visitNodes((node as LocalDecls).declarations, nodeCallback, nodeArrayCallback);
        case SyntaxKind.varDecl:
            return visitNode((node as VariableDecl).name, nodeCallback)
                || visitNode((node as VariableDecl).bindingType, nodeCallback);
        case SyntaxKind.constDecl:
            return visitNode((node as ConstantDeclaration).name, nodeCallback)
                || visitNode((node as ConstantDeclaration).bindingType, nodeCallback)
                || visitNode((node as ConstantDeclaration).initialize, nodeCallback);
        case SyntaxKind.arrayDecl:
            return visitNode((node as ArrayDecl).name, nodeCallback)
                || visitNodes((node as ArrayDecl).dimensions, nodeCallback, nodeArrayCallback)
                || visitNode((node as ArrayDecl).bindingType, nodeCallback);
        case SyntaxKind.funcDecl:
            return visitNode((node as FunctionDeclaration).name, nodeCallback)
                || visitNodes((node as FunctionDeclaration).parameters, nodeCallback, nodeArrayCallback)
                || visitNode((node as FunctionDeclaration).body, nodeCallback);
        // Signatures
        case SyntaxKind.constSignature:
            return visitNode((node as ConstSignature).name, nodeCallback)
                || visitNode((node as ConstSignature).bindingType, nodeCallback);
        case SyntaxKind.parameterSignature:
            return visitNode((node as ParameterSignature).name, nodeCallback)
                || visitNode((node as ParameterSignature).declaration, nodeCallback)
                || visitNode((node as ParameterSignature).paramArray, nodeCallback)
                || visitNode((node as ParameterSignature).optional, nodeCallback)
                || visitNode((node as ParameterSignature).default, nodeCallback);
        case SyntaxKind.propertySignature:
            return visitNode((node as PropertySignature).name, nodeCallback)
                || visitNodes((node as PropertySignature).modifiers, nodeCallback, nodeArrayCallback)
                || visitNodes((node as PropertySignature).parameters, nodeCallback, nodeArrayCallback)
                || visitNode((node as PropertySignature).bindingType, nodeCallback);
        case SyntaxKind.functionSignature:
            return visitNode((node as FunctionSignature).name, nodeCallback)
                || visitNodes((node as FunctionSignature).parameters, nodeCallback, nodeArrayCallback)
                || visitNode((node as FunctionSignature).bindingType, nodeCallback);
        case SyntaxKind.enumMemberSignature:
            return visitNode((node as EnumMemberSignature).name, nodeCallback)
                || visitNode((node as EnumMemberSignature).literal, nodeCallback);
        case SyntaxKind.enumSignature:
            return visitNode((node as EnumSignature).name, nodeCallback)
                || visitNodes((node as EnumSignature).members, nodeCallback, nodeArrayCallback);
        case SyntaxKind.interfaceSignature:
            return visitNode((node as InterfaceSignature).name, nodeCallback)
                || visitNodes((node as InterfaceSignature).inherits, nodeCallback, nodeArrayCallback)
                || visitNodes((node as InterfaceSignature).properties, nodeCallback, nodeArrayCallback)
                || visitNodes((node as InterfaceSignature).methods, nodeCallback, nodeArrayCallback)
                || visitNode((node as InterfaceSignature).default, nodeCallback);
        case SyntaxKind.classSignature:
            return visitNode((node as ClassSignature).name, nodeCallback)
                || visitNodes((node as ClassSignature).inherits, nodeCallback, nodeArrayCallback)
                || visitNodes((node as ClassSignature).implements, nodeCallback, nodeArrayCallback)
                || visitNodes((node as ClassSignature).properties, nodeCallback, nodeArrayCallback)
                || visitNodes((node as ClassSignature).methods, nodeCallback, nodeArrayCallback)
                || visitNodes((node as ClassSignature).constants, nodeCallback, nodeArrayCallback)
                || visitNode((node as ClassSignature).default, nodeCallback);
        case SyntaxKind.moduleSignature:
            return visitNode((node as ModuleSignature).name, nodeCallback)
                || visitNodes((node as ModuleSignature).interfaces, nodeCallback, nodeArrayCallback)
                || visitNodes((node as ModuleSignature).classes, nodeCallback, nodeArrayCallback)
                || visitNodes((node as ModuleSignature).enums, nodeCallback, nodeArrayCallback)
                || visitNodes((node as ModuleSignature).functions, nodeCallback, nodeArrayCallback)
                || visitNodes((node as ModuleSignature).fullName, nodeCallback, nodeArrayCallback)
                || visitNodes((node as ModuleSignature).constants, nodeCallback, nodeArrayCallback);
        case SyntaxKind.bindingType:
            const type = (node as Binding).type;
            return isNodeArray(type) ? visitNodes(type, nodeCallback, nodeArrayCallback) : visitNode(type, nodeCallback);
        case SyntaxKind.arrayTypeSignature:
            return visitNodes((node as ArrayTypeSignature).fullName, nodeCallback, nodeArrayCallback);
        case SyntaxKind.inheritLike:
            return visitNodes((node as InheritLike).fullName, nodeCallback, nodeArrayCallback);

        // Expressions
        case SyntaxKind.unaryExpr:
            return visitNode((node as UnaryExpr).operator, nodeCallback)
                || visitNode((node as UnaryExpr).expression, nodeCallback);
        case SyntaxKind.binaryExpr:
            if (node.isAssignmentExpression()) {
                return visitNode(node.left, nodeCallback)
                    || visitNode(node.right, nodeCallback);
            }
            return visitNode((node as BinaryExpression).left, nodeCallback)
                || visitNode((node as BinaryExpression).right, nodeCallback);
        case SyntaxKind.iteration:
            return visitNode((node as IterationExpr).lower, nodeCallback)
                || visitNode((node as IterationExpr).upper, nodeCallback);
        case SyntaxKind.callExpr:
            return visitNode((node as CallExpr).callee, nodeCallback)
                || visitNodes((node as CallExpr).arguments, nodeCallback, nodeArrayCallback);
        case SyntaxKind.memberExpr:
            return visitNode((node as MemberExpr).object, nodeCallback)
                || visitNode((node as MemberExpr).member, nodeCallback);
        case SyntaxKind.indexExpr:
            return visitNode((node as IndexExpr).object, nodeCallback)
                || visitNode((node as IndexExpr).index, nodeCallback);
        case SyntaxKind.selectCaseComparison:
            return visitNode((node as SelectCaseComparison).operator, nodeCallback)
                || visitNode((node as SelectCaseComparison).right, nodeCallback);
        case SyntaxKind.objectCollectionIterator:
            return visitNode((node as ObjectCollectionIterator).dotDot, nodeCallback)
                || visitNode((node as ObjectCollectionIterator).categories, nodeCallback);

        // Statement
        case SyntaxKind.exprStat:
            return visitNode((node as ExprStat).expression, nodeCallback);
        case SyntaxKind.block:
            return visitNodes((node as Block).statements, nodeCallback, nodeArrayCallback);
        case SyntaxKind.ifStat:
            return visitNode((node as IfStat).condition, nodeCallback)
                || visitNode((node as IfStat).then, nodeCallback)
                || visitNode((node as IfStat).else, nodeCallback);
        case SyntaxKind.forStat:
            return visitNode((node as ForStat).counter, nodeCallback)
                || visitNode((node as ForStat).range, nodeCallback)
                || visitNode((node as ForStat).step, nodeCallback)
                || visitNode((node as ForStat).statement, nodeCallback);
        case SyntaxKind.forEachStat:
            return visitNode((node as ForEachStat).element, nodeCallback)
                || visitNode((node as ForEachStat).group, nodeCallback)
                || visitNode((node as ForEachStat).statement, nodeCallback);
        case SyntaxKind.doStat:
            return visitNode((node as DoStat).expression, nodeCallback)
                || visitNode((node as DoStat).until, nodeCallback)
                || visitNode((node as DoStat).statement, nodeCallback);
        case SyntaxKind.whileStat:
            return visitNode((node as WhileStat).expression, nodeCallback)
                || visitNode((node as WhileStat).statement, nodeCallback);
        case SyntaxKind.withStat:
            return visitNode((node as WithStat).object, nodeCallback)
                || visitNode((node as WithStat).statement, nodeCallback);
        case SyntaxKind.selectCaseClause:
            return visitNodes((node as SelectCaseClause).conditions, nodeCallback, nodeArrayCallback)
                || visitNode((node as SelectCaseClause).statement, nodeCallback);
        case SyntaxKind.selectStat:
            return visitNodes((node as SelectStat).cases, nodeCallback, nodeArrayCallback)
                || visitNode((node as SelectStat).test, nodeCallback);
        case SyntaxKind.sectionStat:
            return visitNode((node as SectionStat).name, nodeCallback)
                || visitNode((node as SectionStat).statement, nodeCallback);
        case SyntaxKind.eventSection:
            return visitNode((node as EventSection).name, nodeCallback)
                || visitNode((node as EventSection).description, nodeCallback)
                || visitNode((node as EventSection).statement, nodeCallback);
        case SyntaxKind.routingSection:
            return visitNode((node as RoutingSection).statement, nodeCallback);
        case SyntaxKind.metadataSection:
            return visitNode((node as MetadataSection).language, nodeCallback)
                || visitNode((node as MetadataSection).context, nodeCallback)
                || visitNode((node as MetadataSection).labelType, nodeCallback)
                || visitNode((node as MetadataSection).dataSource, nodeCallback)
                || visitNode((node as MetadataSection).document, nodeCallback);
        case SyntaxKind.jobSection:
            return visitNode((node as JobSection).name, nodeCallback)
                || visitNode((node as JobSection).description, nodeCallback)
                || visitNode((node as JobSection).tempDirectory, nodeCallback);
        case SyntaxKind.inputDataSourceSection:
            return visitNode((node as InputDataSourceSection).name, nodeCallback)
                || visitNode((node as InputDataSourceSection).description, nodeCallback)
                || visitNode((node as InputDataSourceSection).connectionString, nodeCallback)
                || visitNode((node as InputDataSourceSection).selectQuery, nodeCallback)
                || visitNode((node as InputDataSourceSection).updateQuery, nodeCallback)
                || visitNode((node as InputDataSourceSection).useInputAsOutput, nodeCallback)
                || visitNode((node as InputDataSourceSection).joinKeySorted, nodeCallback)
                || visitNode((node as InputDataSourceSection).joinType, nodeCallback)
                || visitNode((node as InputDataSourceSection).joinKey, nodeCallback);
        case SyntaxKind.outputDataSourceSection:
            return visitNode((node as OutputDataSourceSection).name, nodeCallback)
                || visitNode((node as OutputDataSourceSection).description, nodeCallback)
                || visitNode((node as OutputDataSourceSection).connectionString, nodeCallback)
                || visitNode((node as OutputDataSourceSection).metadataDataOutputName, nodeCallback)
                || visitNode((node as OutputDataSourceSection).updateQuery, nodeCallback)
                || visitNode((node as OutputDataSourceSection).tableOutputName, nodeCallback)
                || visitNode((node as OutputDataSourceSection).variableOrder, nodeCallback);
        case SyntaxKind.globalSQLVariablesSection:
            return visitNode((node as GlobalSQLVariablesSection).name, nodeCallback)
                || visitNode((node as GlobalSQLVariablesSection).description, nodeCallback)
                || visitNode((node as GlobalSQLVariablesSection).connectionString, nodeCallback)
                || visitNode((node as GlobalSQLVariablesSection).selectQuery, nodeCallback);
        case SyntaxKind.loggingSection:
            return visitNode((node as LoggingSection).name, nodeCallback)
                || visitNode((node as LoggingSection).description, nodeCallback)
                || visitNode((node as LoggingSection).group, nodeCallback)
                || visitNode((node as LoggingSection).path, nodeCallback)
                || visitNode((node as LoggingSection).alias, nodeCallback)
                || visitNode((node as LoggingSection).fileSize, nodeCallback);
        case SyntaxKind.jumpStat:
            return visitNode((node as JumpStatement).exit, nodeCallback)
                || visitNode((node as JumpStatement).exitPrecedure, nodeCallback)
                || visitNode((node as JumpStatement).goto, nodeCallback)
                || visitNode((node as JumpStatement).location, nodeCallback)
                || visitNode((node as JumpStatement).on, nodeCallback)
                || visitNode((node as JumpStatement).error, nodeCallback)
                || visitNode((node as JumpStatement).resume, nodeCallback);
        case SyntaxKind.resumeStat:
            return visitNode((node as ResumeStatement).resume, nodeCallback)
                || visitNode((node as ResumeStatement).next, nodeCallback);
        case SyntaxKind.location:
            return visitNode((node as LineLocation).name, nodeCallback);

        // Metadata
        case SyntaxKind.mdmDocument:
            return visitNodes((node as MDMDocument).types, nodeCallback, nodeArrayCallback)
                || visitNodes((node as MDMDocument).fields, nodeCallback, nodeArrayCallback)
                || visitNodes((node as MDMDocument).lcl, nodeCallback, nodeArrayCallback)
                || visitNode((node as MDMDocument).hdata, nodeCallback)
                || visitNodes((node as MDMDocument).preprocessor, nodeCallback, nodeArrayCallback);
        case SyntaxKind.mdmAreaName:
            return visitNode((node as MDMAreaName).areaName, nodeCallback)
                || visitNode((node as MDMAreaName).language, nodeCallback)
                || visitNode((node as MDMAreaName).context, nodeCallback)
                || visitNode((node as MDMAreaName).labelType, nodeCallback);
        case SyntaxKind.mdmProperty:
            return visitNode((node as MDMProperty).name, nodeCallback)
                || visitNode((node as MDMProperty).value, nodeCallback);
        case SyntaxKind.mdmTemplate:
            return visitNode((node as MDMTemplate).name, nodeCallback)
                || visitNode((node as MDMTemplate).value, nodeCallback);
        case SyntaxKind.mdmProperties:
            return visitNode((node as MDMProperties).name, nodeCallback)
                || (node as MDMProperties).forEachChild(nodeCallback, nodeArrayCallback);
        case SyntaxKind.mdmTemplates:
            return visitNode((node as MDMTemplates).name, nodeCallback)
                || (node as MDMTemplates).forEachChild(nodeCallback, nodeArrayCallback);
        case SyntaxKind.mdmControlStyle:
            return visitNode((node as MDMControlStyle).name, nodeCallback)
                || visitNode((node as MDMControlStyle).accelerator, nodeCallback)
                || visitNode((node as MDMControlStyle).readOnly, nodeCallback)
                || visitNode((node as MDMControlStyle).type, nodeCallback);
        case SyntaxKind.mdmCellStyle:
            return visitNode((node as MDMCellStyle).name, nodeCallback)
                || visitNode((node as MDMCellStyle).width, nodeCallback)
                || visitNode((node as MDMCellStyle).height, nodeCallback)
                || visitNode((node as MDMCellStyle).borderColor, nodeCallback)
                || visitNode((node as MDMCellStyle).borderTopColor, nodeCallback)
                || visitNode((node as MDMCellStyle).borderRightColor, nodeCallback)
                || visitNode((node as MDMCellStyle).borderBottomColor, nodeCallback)
                || visitNode((node as MDMCellStyle).borderLeftColor, nodeCallback)
                || visitNode((node as MDMCellStyle).borderStyle, nodeCallback)
                || visitNode((node as MDMCellStyle).borderWidth, nodeCallback)
                || visitNode((node as MDMCellStyle).borderTopWidth, nodeCallback)
                || visitNode((node as MDMCellStyle).borderRightWidth, nodeCallback)
                || visitNode((node as MDMCellStyle).borderBottomWidth, nodeCallback)
                || visitNode((node as MDMCellStyle).borderLeftWidth, nodeCallback)
                || visitNode((node as MDMCellStyle).borderTopStyle, nodeCallback)
                || visitNode((node as MDMCellStyle).borderRightStyle, nodeCallback)
                || visitNode((node as MDMCellStyle).borderBottomStyle, nodeCallback)
                || visitNode((node as MDMCellStyle).borderLeftStyle, nodeCallback)
                || visitNode((node as MDMCellStyle).padding, nodeCallback)
                || visitNode((node as MDMCellStyle).paddingTop, nodeCallback)
                || visitNode((node as MDMCellStyle).paddingRight, nodeCallback)
                || visitNode((node as MDMCellStyle).paddingBottom, nodeCallback)
                || visitNode((node as MDMCellStyle).paddingLeft, nodeCallback)
                || visitNode((node as MDMCellStyle).wrap, nodeCallback)
                || visitNode((node as MDMCellStyle).colSpan, nodeCallback)
                || visitNode((node as MDMCellStyle).rowSpan, nodeCallback)
                || visitNode((node as MDMCellStyle).bgColor, nodeCallback)
                || visitNode((node as MDMCellStyle).repeatHeader, nodeCallback);
        case SyntaxKind.mdmFontStyle:
            return visitNode((node as MDMFontStyle).name, nodeCallback)
                || visitNode((node as MDMFontStyle).family, nodeCallback)
                || visitNode((node as MDMFontStyle).size, nodeCallback)
                || visitNode((node as MDMFontStyle).isUnderline, nodeCallback)
                || visitNode((node as MDMFontStyle).isItalic, nodeCallback)
                || visitNode((node as MDMFontStyle).isBold, nodeCallback)
                || visitNode((node as MDMFontStyle).isStrikethrough, nodeCallback)
                || visitNode((node as MDMFontStyle).isOverline, nodeCallback)
                || visitNode((node as MDMFontStyle).isBlink, nodeCallback)
                || visitNode((node as MDMFontStyle).isSuperscript, nodeCallback)
                || visitNode((node as MDMFontStyle).isSubscript, nodeCallback);
        case SyntaxKind.mdmStyle:
            return visitNode((node as MDMStyle).name, nodeCallback)
                || visitNode((node as MDMStyle).font, nodeCallback)
                || visitNode((node as MDMStyle).cell, nodeCallback)
                || visitNode((node as MDMStyle).control, nodeCallback)
                || visitNode((node as MDMStyle).color, nodeCallback)
                || visitNode((node as MDMStyle).bgColor, nodeCallback)
                || visitNode((node as MDMStyle).hidden, nodeCallback)
                || visitNode((node as MDMStyle).align, nodeCallback)
                || visitNode((node as MDMStyle).verticalAlign, nodeCallback)
                || visitNode((node as MDMStyle).elementAlign, nodeCallback)
                || visitNode((node as MDMStyle).indent, nodeCallback)
                || visitNode((node as MDMStyle).zIndex, nodeCallback)
                || visitNode((node as MDMStyle).cursor, nodeCallback)
                || visitNode((node as MDMStyle).image, nodeCallback)
                || visitNode((node as MDMStyle).imagePosition, nodeCallback)
                || visitNode((node as MDMStyle).orientation, nodeCallback)
                || visitNode((node as MDMStyle).columns, nodeCallback)
                || visitNode((node as MDMStyle).rows, nodeCallback)
                || visitNode((node as MDMStyle).width, nodeCallback)
                || visitNode((node as MDMStyle).height, nodeCallback);
        case SyntaxKind.mdmLabel:
            return (node as MDMLabel).forEachChild(nodeCallback, nodeArrayCallback)
                || visitNode((node as MDMLabel).label, nodeCallback);
        case SyntaxKind.mdmElementType:
            return visitNode((node as MDMCategoryElementType).name, nodeCallback);
        case SyntaxKind.mdmCategoryExpression:
            return visitNode((node as MDMCategoryExpression).name, nodeCallback);
        case SyntaxKind.mdmFactor:
            return visitNode((node as MDMFactor).name, nodeCallback);
        case SyntaxKind.mdmKeycode:
            return visitNode((node as MDMKeycode).name, nodeCallback);
        case SyntaxKind.mdmMultiplier:
            return visitNode((node as MDMMultiplier).name, nodeCallback)
                || visitNode((node as MDMMultiplier).field, nodeCallback);
        case SyntaxKind.mdmOther:
            return visitNode((node as MDMOther).field, nodeCallback);
        case SyntaxKind.mdmCategory:
            return visitNode((node as MDMCategory).name, nodeCallback)
                || visitNode((node as MDMCategory).label, nodeCallback)
                || visitNode((node as MDMCategory).properties, nodeCallback)
                || visitNode((node as MDMCategory).templates, nodeCallback)
                || visitNode((node as MDMCategory).labelStyle, nodeCallback)
                || visitNode((node as MDMCategory).style, nodeCallback)
                || visitNode((node as MDMCategory).multiplier, nodeCallback)
                || visitNode((node as MDMCategory).other, nodeCallback)
                || visitNode((node as MDMCategory).na, nodeCallback)
                || visitNode((node as MDMCategory).ref, nodeCallback)
                || visitNode((node as MDMCategory).dk, nodeCallback)
                || visitNode((node as MDMCategory).exclusive, nodeCallback)
                || visitNode((node as MDMCategory).factor, nodeCallback)
                || visitNode((node as MDMCategory).keycode, nodeCallback)
                || visitNode((node as MDMCategory).expression, nodeCallback)
                || visitNode((node as MDMCategory).elementType, nodeCallback)
                || visitNode((node as MDMCategory).canfilter, nodeCallback)
                || visitNode((node as MDMCategory).nofilter, nodeCallback)
                || visitNode((node as MDMCategory).listName, nodeCallback)
                || visitNode((node as MDMCategory).list, nodeCallback)
                || visitNode((node as MDMCategory).categories, nodeCallback)
                || visitNode((node as MDMCategory).namespace, nodeCallback);
        case SyntaxKind.mdmCategories:
            return (node as MDMCategories).forEachChild(nodeCallback, nodeArrayCallback)
                || visitNode((node as MDMCategories).namespace, nodeCallback);
        case SyntaxKind.mdmHierarchicalView:
            return visitNode((node as MDMHierarchicalView).name, nodeCallback)
                || visitNode((node as MDMHierarchicalView).label, nodeCallback)
                || visitNode((node as MDMHierarchicalView).properties, nodeCallback)
                || visitNode((node as MDMHierarchicalView).templates, nodeCallback)
                || visitNode((node as MDMHierarchicalView).labelStyle, nodeCallback)
                || visitNode((node as MDMHierarchicalView).style, nodeCallback);
        case SyntaxKind.mdmUsageType:
            return visitNode((node as MDMUsageType).value, nodeCallback);
        case SyntaxKind.mdmClass:
            return visitNode((node as MDMClass).name, nodeCallback)
                || visitNodes((node as MDMClass).types, nodeCallback, nodeArrayCallback)
                || visitNodes((node as MDMClass).fields, nodeCallback, nodeArrayCallback)
                || visitNodes((node as MDMClass).pages, nodeCallback, nodeArrayCallback);
        case SyntaxKind.mdmCodes:
            return visitNode((node as MDMCodes).name, nodeCallback)
                || visitNode((node as MDMCodes).useField, nodeCallback)
                || visitNodes((node as MDMCodes).value, nodeCallback, nodeArrayCallback);
        case SyntaxKind.mdmPrecision:
        case SyntaxKind.mdmScale:
        case SyntaxKind.mdmValidation:
        case SyntaxKind.mdmInitialAnswer:
        case SyntaxKind.mdmDefaultAnswer:
        case SyntaxKind.mdmAxis:
            return visitNode((node as MDMDeclarationValueLike<MDMDeclarationKind, Node>).name, nodeCallback)
                || visitNode((node as MDMDeclarationValueLike<MDMDeclarationKind, Node>).value, nodeCallback);
        case SyntaxKind.mdmField:
            result = visitNode((node as MDMField).name, nodeCallback)
                || visitNode((node as MDMField).label, nodeCallback)
                || visitNode((node as MDMField).properties, nodeCallback)
                || visitNode((node as MDMField).templates, nodeCallback)
                || visitNode((node as MDMField).labelStyle, nodeCallback)
                || visitNode((node as MDMField).style, nodeCallback)
                || visitNode((node as MDMField).categories, nodeCallback)
                || visitNode((node as MDMField).class, nodeCallback)
                || visitNode((node as MDMField).row, nodeCallback)
                || visitNode((node as MDMField).column, nodeCallback)
                || visitNode((node as MDMField).expand, nodeCallback)
                || visitNode((node as MDMField).grid, nodeCallback)
                || visitNode((node as MDMField).precision, nodeCallback)
                || visitNode((node as MDMField).codes, nodeCallback)
                || visitNode((node as MDMField).validation, nodeCallback)
                || visitNode((node as MDMField).expression, nodeCallback)
                || visitNode((node as MDMField).initialAnswer, nodeCallback)
                || visitNode((node as MDMField).defaultAnswer, nodeCallback)
                || visitNode((node as MDMField).axis, nodeCallback)
                || visitNode((node as MDMField).usageType, nodeCallback)
                || visitNode((node as MDMField).helperFields, nodeCallback)
                || visitNode((node as MDMField).noCaseData, nodeCallback)
                || visitNode((node as MDMField).unversioned, nodeCallback);
            if (result || (!node.isMDMDbQuestions() && !node.isMDMPage())) {
                return result;
            }
            if (node.isMDMPage()) {
                return visitNodes((node as MDMPage).questionNames, nodeCallback, nodeArrayCallback);
            }
            return visitNode((node as MDMDbQuestions).connectionString, nodeCallback)
                || visitNode((node as MDMDbQuestions).table, nodeCallback)
                || visitNode((node as MDMDbQuestions).minAnswers, nodeCallback)
                || visitNode((node as MDMDbQuestions).maxAnswers, nodeCallback)
                || visitNode((node as MDMDbQuestions).sqlFilter, nodeCallback)
                || visitNode((node as MDMDbQuestions).cacheTimeout, nodeCallback)
                || visitNode((node as MDMDbQuestions).iteratorIDType, nodeCallback)
                || visitNode((node as MDMDbQuestions).columns?.columnId, nodeCallback)
                || visitNode((node as MDMDbQuestions).columns?.columnLabel, nodeCallback)
                || visitNode((node as MDMDbQuestions).columns?.columnKeycode, nodeCallback)
                || visitNode((node as MDMDbQuestions).columns?.columnFile, nodeCallback)
                || visitNode((node as MDMDbQuestions).columns?.columnAnalysisValue, nodeCallback)
                || visitNode((node as MDMDbQuestions).columns?.columnFixed, nodeCallback)
                || visitNode((node as MDMDbQuestions).columns?.columnExclusive, nodeCallback);

        // Preprocessor
        case SyntaxKind.ppInclude:
            return visitNode((node as PPInclude).path, nodeCallback);
        case SyntaxKind.ppDefine:
            const definition = (node as PPDefine).definition;
            let definitionResult = undefined;
            if (definition) {
                if (isNodeArray(definition)) {
                    definitionResult = visitNodes(definition, nodeCallback, nodeArrayCallback);
                } else if (isNode(definition)) {
                    definitionResult = visitNode(definition, nodeCallback);
                }
            }
            return visitNode((node as PPDefine).name, nodeCallback)
                || definitionResult
                || visitNodes((node as PPDefine).parameters, nodeCallback, nodeArrayCallback);
        case SyntaxKind.ppUndef:
            return visitNode((node as PPUndef).name, nodeCallback);
        case SyntaxKind.ppIf:
            return visitNode((node as PPIf).condition, nodeCallback)
                || visitNode((node as PPIf).then, nodeCallback)
                || visitNode((node as PPIf).else, nodeCallback);
        case SyntaxKind.ppIfDef:
            return visitNode((node as PPIfDef).macroName, nodeCallback)
                || visitNode((node as PPIfDef).then, nodeCallback)
                || visitNode((node as PPIfDef).else, nodeCallback);
        case SyntaxKind.ppIfNDef:
            return visitNode((node as PPIfNDef).macroName, nodeCallback)
                || visitNode((node as PPIfNDef).then, nodeCallback)
                || visitNode((node as PPIfNDef).else, nodeCallback);
        case SyntaxKind.sourceFile:
            return visitNodes((node as SourceFile).macroNodes, nodeCallback, nodeArrayCallback)
                || visitNodes((node as SourceFile).statements, nodeCallback, nodeArrayCallback)
                || visitNode((node as SourceFile).metadata, nodeCallback);
    }

    //return visitNode(node, nodeCallback);
}

export function visitNode<T>(node: Node | undefined, callback: (node: Node) => T | undefined): T | undefined {
    return node && callback(node);
}

export function visitNodes<T>(nodes: NodeArray<Node> | undefined, nodeCallback: (node: Node) => T | undefined, nodeArrayCallback: ((nodeArray: NodeArray<Node>) => T | undefined) | undefined): T | undefined {
    if (nodes) {
        if (nodeArrayCallback) {
            return nodeArrayCallback(nodes);
        }
        for (const node of nodes) {
            const result = nodeCallback(node);
            if (result) {
                return result;
            }
        }
    }
}

export function stringIsCorrectLength(str: string): boolean {
    return /^((\d+)|(\d+\.\d+))(%|cm|em|ex|in|mm|pc|pt|px)$/i.test(str.replace(/\s*/g, ""));
}

const commentReferenceChildPattern = /^['\s]*\<\s*include\s+file\s*=\s*"((?:[^\"]|\.)*)"\s*\/\>\s*$/i;
const commentReferenceParentPattern = /^['\s]*\<\s*reference\s+file\s*=\s*"((?:[^\"]|\.)*)"\s+name\s*=\s*"((?:[^\"]|\.)*)"\s*\/\>\s*$/i;

export function getCommentReferenceChild(str: string): string | undefined {
    const regex = new RegExp(commentReferenceChildPattern.source);
    const matches = regex.exec(str);
    return matches && matches.length > 1 ? matches[1] : undefined;
}

export function getCommentReference(str: string): {
    fileName: string;
    value: string;
    span: TextSpan;
} | string | undefined {
    let referenceParentRegex = new RegExp(commentReferenceParentPattern.source);
    let parentResult = referenceParentRegex.exec(str);
    if (parentResult && parentResult.length === 3) {
        let resultStart = str.indexOf(parentResult[0]);
        return {
            fileName: parentResult[1],
            value: parentResult[2],
            span: {
                start: resultStart,
                length: parentResult[0].length
            }
        };
    }
    let referenceChildRegex = new RegExp(commentReferenceChildPattern.source);
    let childResult = referenceChildRegex.exec(str);
    if (childResult && childResult.length === 2) {
        return childResult[1];
    }
}

export function isCommentMetadataFileFlag(str: string): boolean {
    return /^['\s]*metadata$/i.test(str);
}

export function isCommentScriptMrsFileFlag(str: string): boolean {
    return /^['\s]*script-mrs$/i.test(str);
}

export function isCommentScriptDmsFileFlag(str: string): boolean {
    return /^['\s]*script-dms$/i.test(str);
}

export function isCommentScriptIgnoreTypeError(str: string): boolean{
    return /^['\s]*ignore-type-error$/i.test(str);
}

export enum Comparison {
    lessThan    = -1,
    equal       = 0,
    greaterThan = 1,
}

export type Comparer<T> = (value1: T, value2: T) => Comparison;

export function binarySearch<T>(array: readonly T[], searchValue: T, comparer: Comparer<T>, offset?: number) {
    let low = offset || 0;
    let high = array.length - 1;
    while (low <= high) {
        let mid = low + ((high - low) >> 1);
        let comparison = comparer(array[mid], searchValue);
        switch (comparison) {
            case Comparison.equal:
                return mid;
            case Comparison.greaterThan:
                high = mid - 1;
                break;
            case Comparison.lessThan:
                low = mid + 1;
                break;
        }
    }
    return ~low;
}

export function compareNumberValue(num1: number, num2: number): Comparison {
    return num1 === num2 ? Comparison.equal : (num1 > num2 ? Comparison.greaterThan : Comparison.lessThan);
}

export function removeStringQuotation(text: string): string {
    let result = text;
    if (result.length >= 2 && result.startsWith("\"") && result.endsWith("\"")) {
        result = result.substring(1, result.length - 1);
    }
    return normalizeLineFeedCharacter(result);
}

// Text Range

export function createTextRange(start: number, end: number): TextRange {
    return { start, end };
}

export function setTextRangeStart<T extends ReadonlyTextRange>(range: T, start: number): ReadonlyTextRange {
    (range as TextRange).start = start;
    return range;
}

export function setTextRangeEnd<T extends ReadonlyTextRange>(range: T, end: number): ReadonlyTextRange {
    (range as TextRange).end = end;
    return range;
}

export function setTextRangeStartEnd<T extends ReadonlyTextRange>(range: T, start: number, end: number): ReadonlyTextRange {
    return setTextRangeEnd(setTextRangeStart(range, start), end);
}

export function setTextRangeStartWidth<T extends ReadonlyTextRange>(range: T, start: number, width: number): ReadonlyTextRange {
    return setTextRangeStartEnd(range, start, start + width);
}

export function createTextChangeRange(start: number, length: number, newLength: number): TextChangeRange {
    if (newLength < 0) {
        throw new Error("TextChangeRange newLength < 0");
    }
    return { start, length, newLength };
}

export function textChangeRangeIsEmpty(range: TextChangeRange) {
    return range.length === 0 && range.newLength === 0;
}

export function isTextChangeRangeUnchanged(range: TextChangeRange) {
    return range.length === 0 && range.newLength === 0;
}

export function isTextPositionEqual(pos1: TextPosition, pos2: TextPosition) {
    return pos1.line === pos2.line && pos1.character === pos2.character;
}

export function isTextSpanEqual(arg1: TextSpan, arg2: TextSpan) {
    return arg1.start === arg2.start && arg1.length === arg2.length;
}

export function isPositionInSpan(position: number, span: TextSpan) {
    return position > span.start && position < (span.start + span.length);
}

export function getTextSpanEnd(span: TextSpan) {
    return span.start + span.length;
}

//

export function getLineStarts(sourceFile: SourceFile): readonly number[] {
    return (sourceFile.lineMap || (sourceFile.lineMap = computeLineStarts(sourceFile.text)));
}

export function lastOfArray<T>(array: readonly T[]): T | undefined {
    return array.length === 0 ? undefined : array[array.length - 1];
}

export function mergeSymbolMap(maps: ReadonlyMap<string, Symbol>[], conflictCallback?: (current: Symbol, exist: Symbol, table: ReadonlyMap<string, Symbol>) => void): Map<string, Symbol> {
    const result = new Map<string, Symbol>();
    for (const map of maps) {
        map.forEach((v, k) => {
            let exist = result.get(k);
            if (exist) {
                conflictCallback?.(v, exist, result);
            }
            else {
                result.set(k, v);
            }
        });
    }
    return result;
}

export function mergeSymbolMapTo(confilctCallback: ((current: Symbol, exist: Symbol, table: ReadonlyMap<string, Symbol>) => void) | undefined, baseMap: Map<string, Symbol>, ...tables: (ReadonlyMap<string, Symbol> | undefined)[]): ReadonlyMap<string, Symbol> {
    for (const table of tables) {
        if (!table) {
            continue;
        }
        table.forEach((v, k) => {
            let exist = baseMap.get(k);
            if (exist) {
                confilctCallback?.(v, exist, baseMap);
            }
            else {
                baseMap.set(k, v);
            }
        });
    }
    return baseMap;
}

export function updateSymbolTable(baseMap: ReadonlySymbolTable, insertTable: ReadonlySymbolTable, replaceWhenExist?: boolean) {
    insertTable.forEach(symbol => {
        if (!baseMap.has(symbol.escapedName) || replaceWhenExist) {
            (baseMap as SymbolTable).set(symbol);
        }
    });
}

export function arrayIndexOf<T>(array: T[], precidate: (i: T) => boolean): number {
    for (let index = 0; index < array.length; index++) {
        const element = array[index];
        if (precidate(element)) {
            return index;
        }
    }
    return -1;
}

// lexer

export function isIdentifierOrReservedWord(flag: SyntaxKind): boolean {
    return flag === SyntaxKind.identifier
        || (flag >= SyntaxKind.firstKeyword && flag <= SyntaxKind.lastKeyword)
        || (flag >= SyntaxKind.firstSectionKeyword && flag <= SyntaxKind.lastSectionKeyword)
        || (flag >= SyntaxKind.firstMDMKeyword && flag <= SyntaxKind.lastMDMKeyword)
        || (flag >= SyntaxKind.firstDeclareKeyword && flag <= SyntaxKind.lastDeclareKeyword);
}

export function isReservedWord(flag: SyntaxKind, fileFlag: FileKind): boolean {
    let result = flag >= SyntaxKind.firstKeyword && flag <= SyntaxKind.lastKeyword;
    if (!result && fileFlag === FileKind.declare) {
        result = flag >= SyntaxKind.firstDeclareKeyword && flag <= SyntaxKind.lastDeclareKeyword;
    }
    if (!result && fileFlag === FileKind.mdd) {
        result = flag >= SyntaxKind.firstMDMKeyword && flag <= SyntaxKind.lastMDMKeyword;
    }
    return result;
}

export function stringIsPreprocessorKeyword(text: string): boolean {
    return /if|ifdef|ifndef|else|elif|endif|define|undef|include|line|error/.test(text);
}

/**
 * 将预处理器使用的C语言操作符转换为对应的DS脚本操作符
 * @param token
 * @returns
 */
export function convertPPOperatorToEquivalentToken(token: SyntaxKind): SyntaxKind {
    switch (token) {
        case SyntaxKind.barbar:                  return SyntaxKind.orKeyword;
        case SyntaxKind.ampersandAmpersand:      return SyntaxKind.andKeyword;
        case SyntaxKind.exclamation:             return SyntaxKind.notKeyword;
        case SyntaxKind.exclamationEqual:        return SyntaxKind.notEqual;
        case SyntaxKind.equalEqual:              return SyntaxKind.equal;
        default:                                 break;
    }
    return token;
}

const unicodeIdentifierStart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 543, 546, 563, 592, 685, 688, 696, 699, 705, 720, 721, 736, 740, 750, 750, 890, 890, 902, 902, 904, 906, 908, 908, 910, 929, 931, 974, 976, 983, 986, 1011, 1024, 1153, 1164, 1220, 1223, 1224, 1227, 1228, 1232, 1269, 1272, 1273, 1329, 1366, 1369, 1369, 1377, 1415, 1488, 1514, 1520, 1522, 1569, 1594, 1600, 1610, 1649, 1747, 1749, 1749, 1765, 1766, 1786, 1788, 1808, 1808, 1810, 1836, 1920, 1957, 2309, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2524, 2525, 2527, 2529, 2544, 2545, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2699, 2701, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2784, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2870, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 2997, 2999, 3001, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3168, 3169, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3294, 3294, 3296, 3297, 3333, 3340, 3342, 3344, 3346, 3368, 3370, 3385, 3424, 3425, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3805, 3840, 3840, 3904, 3911, 3913, 3946, 3976, 3979, 4096, 4129, 4131, 4135, 4137, 4138, 4176, 4181, 4256, 4293, 4304, 4342, 4352, 4441, 4447, 4514, 4520, 4601, 4608, 4614, 4616, 4678, 4680, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4742, 4744, 4744, 4746, 4749, 4752, 4782, 4784, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4814, 4816, 4822, 4824, 4846, 4848, 4878, 4880, 4880, 4882, 4885, 4888, 4894, 4896, 4934, 4936, 4954, 5024, 5108, 5121, 5740, 5743, 5750, 5761, 5786, 5792, 5866, 6016, 6067, 6176, 6263, 6272, 6312, 7680, 7835, 7840, 7929, 7936, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8319, 8319, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8497, 8499, 8505, 8544, 8579, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12346, 12353, 12436, 12445, 12446, 12449, 12538, 12540, 12542, 12549, 12588, 12593, 12686, 12704, 12727, 13312, 19893, 19968, 40869, 40960, 42124, 44032, 55203, 63744, 64045, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65138, 65140, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500, ];
const unicodeIdentifierPart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 543, 546, 563, 592, 685, 688, 696, 699, 705, 720, 721, 736, 740, 750, 750, 768, 846, 864, 866, 890, 890, 902, 902, 904, 906, 908, 908, 910, 929, 931, 974, 976, 983, 986, 1011, 1024, 1153, 1155, 1158, 1164, 1220, 1223, 1224, 1227, 1228, 1232, 1269, 1272, 1273, 1329, 1366, 1369, 1369, 1377, 1415, 1425, 1441, 1443, 1465, 1467, 1469, 1471, 1471, 1473, 1474, 1476, 1476, 1488, 1514, 1520, 1522, 1569, 1594, 1600, 1621, 1632, 1641, 1648, 1747, 1749, 1756, 1759, 1768, 1770, 1773, 1776, 1788, 1808, 1836, 1840, 1866, 1920, 1968, 2305, 2307, 2309, 2361, 2364, 2381, 2384, 2388, 2392, 2403, 2406, 2415, 2433, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2492, 2494, 2500, 2503, 2504, 2507, 2509, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2562, 2562, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2649, 2652, 2654, 2654, 2662, 2676, 2689, 2691, 2693, 2699, 2701, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2784, 2790, 2799, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2870, 2873, 2876, 2883, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2913, 2918, 2927, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 2997, 2999, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3031, 3031, 3047, 3055, 3073, 3075, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3134, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3168, 3169, 3174, 3183, 3202, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3262, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3297, 3302, 3311, 3330, 3331, 3333, 3340, 3342, 3344, 3346, 3368, 3370, 3385, 3390, 3395, 3398, 3400, 3402, 3405, 3415, 3415, 3424, 3425, 3430, 3439, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3769, 3771, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3805, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3946, 3953, 3972, 3974, 3979, 3984, 3991, 3993, 4028, 4038, 4038, 4096, 4129, 4131, 4135, 4137, 4138, 4140, 4146, 4150, 4153, 4160, 4169, 4176, 4185, 4256, 4293, 4304, 4342, 4352, 4441, 4447, 4514, 4520, 4601, 4608, 4614, 4616, 4678, 4680, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4742, 4744, 4744, 4746, 4749, 4752, 4782, 4784, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4814, 4816, 4822, 4824, 4846, 4848, 4878, 4880, 4880, 4882, 4885, 4888, 4894, 4896, 4934, 4936, 4954, 4969, 4977, 5024, 5108, 5121, 5740, 5743, 5750, 5761, 5786, 5792, 5866, 6016, 6099, 6112, 6121, 6160, 6169, 6176, 6263, 6272, 6313, 7680, 7835, 7840, 7929, 7936, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8255, 8256, 8319, 8319, 8400, 8412, 8417, 8417, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8497, 8499, 8505, 8544, 8579, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12346, 12353, 12436, 12441, 12442, 12445, 12446, 12449, 12542, 12549, 12588, 12593, 12686, 12704, 12727, 13312, 19893, 19968, 40869, 40960, 42124, 44032, 55203, 63744, 64045, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65056, 65059, 65075, 65076, 65101, 65103, 65136, 65138, 65140, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65381, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500, ];

function lookupInUnicodeMap(code: number, map: readonly number[]): boolean {

    if (code < map[0]) {
        return false;
    }

    // Binary search
    let lo = 0;
    let hi = map.length;
    let mid: number;

    while (lo + 1 < hi) {
        mid = lo + (hi - lo) / 2;
        mid -= mid % 2;
        if (map[mid] <= code && code <= map[mid + 1]) {
            return true;
        }

        if (code < map[mid]) {
            hi = mid;
        }
        else {
            lo = mid + 2;
        }
    }

    return false;
}

export function isUnicodeIdentifierStart(code: number): boolean {
    return lookupInUnicodeMap(code, unicodeIdentifierStart);
}

export function isUnicodeIdentifierPart(code: number): boolean {
    return lookupInUnicodeMap(code, unicodeIdentifierPart);
}

export function isIdentifierStart(code: number | undefined): boolean {
    return code !== undefined && (
        (code >= CharacterCodes.lowercaseA && code <= CharacterCodes.lowercaseZ) ||
        (code >= CharacterCodes.uppercaseA && code <= CharacterCodes.uppercaseZ) ||
        code === CharacterCodes.underscore || code === CharacterCodes.dollarSign ||
        code === CharacterCodes.atSign || code === CharacterCodes.numberSign || isUnicodeIdentifierStart(code));
}

export function isIdentifierPart(code: number | undefined): boolean {
    return code !== undefined && (isIdentifierStart(code) || isDigit(code));
}

export function isPreprocessorStart(code: number): boolean {
    return code === CharacterCodes.lowercaseI ||
        code === CharacterCodes.lowercaseD ||
        code === CharacterCodes.lowercaseE ||
        code === CharacterCodes.lowercaseL ||
        code === CharacterCodes.lowercaseU;
}

export function isAlphabet(code: number | undefined) {
    return code !== undefined && (
        (code >= CharacterCodes.lowercaseA && code <= CharacterCodes.lowercaseZ) ||
        (code >= CharacterCodes.uppercaseA && code <= CharacterCodes.uppercaseZ)
    );
}

export function isDigit(code: number | undefined) {
    return code !== undefined && (code >= CharacterCodes.digit0 && code <= CharacterCodes.digit9);
}

export function isHexNumber(code: number | undefined): boolean {
    return code !== undefined && (isDigit(code) || (code >= CharacterCodes.uppercaseA && code <= CharacterCodes.uppercaseF) || (code >= CharacterCodes.lowercaseA && code <= CharacterCodes.lowercaseF));
}

export function isOctalNumber(code: number | undefined): boolean {
    return code !== undefined && (code >= CharacterCodes.digit0 && code <= CharacterCodes.digit7);
}

export function isLineBreak(code: number | undefined): boolean {
    return code !== undefined && (code === CharacterCodes.lineFeed || code === CharacterCodes.carriageReturn || code === CharacterCodes.lineSeparator || code === CharacterCodes.paragraphSeparator);
}

export function isCodePoint(code: number): boolean {
    return code <= 0x10FFFF;
}

export function isExpressionOrStringLineBreakCharactor(code: number | undefined): boolean {
    return code !== undefined && (code === CharacterCodes.underscore || code === CharacterCodes.backslash);
}

/* @internal */
export const codePointAt: (s: string, i: number) => number = (String.prototype as any).codePointAt ? (s, i) => (s as any).codePointAt(i) : function codePointAt(str, i): number {
    // from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/codePointAt
    const size = str.length;
    // Account for out-of-bounds indices:
    if (i < 0 || i >= size) {
        return undefined!; // String.codePointAt returns `undefined` for OOB indexes
    }
    // Get the first code unit
    const first = str.charCodeAt(i);
    // check if it’s the start of a surrogate pair
    if (first >= 0xD800 && first <= 0xDBFF && size > i + 1) { // high surrogate and there is a next code unit
        const second = str.charCodeAt(i + 1);
        if (second >= 0xDC00 && second <= 0xDFFF) { // low surrogate
            // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
            return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;
        }
    }
    return first;
};

/* @internal */
export function charSize(ch: number) {
    if (ch >= 0x10000) {
        return 2;
    }
    return 1;
}

export function isWhiteSpaceSingleLine(code: number): boolean {
    return code === CharacterCodes.space ||
        code === CharacterCodes.tab   ||
        code === CharacterCodes.oghamSpaceMark;
}

export function isWhiteSpaceLike(code: number): boolean {
    return isWhiteSpaceSingleLine(code) || isLineBreak(code);
}

export function computeLineStarts(text: string): number[] {
    const result: number[] = [];
    let pos = 0;
    let lineStart = 0;
    while (pos < text.length) {
        const ch = text.charCodeAt(pos);
        pos++;
        switch (ch) {
            case CharacterCodes.carriageReturn:
                if (text.charCodeAt(pos) === CharacterCodes.lineFeed) {
                    pos++;
                }

            case CharacterCodes.lineFeed:
                result.push(lineStart);
                lineStart = pos;
                break;

            default:
                if (ch > CharacterCodes.maxAsciiCharacter && isLineBreak(ch)) {
                    result.push(lineStart);
                    lineStart = pos;
                }
                break;
        }
    }
    result.push(lineStart);
    return result;
}

export function computeLineOfPosition(lineStarts: readonly number[], position: number, offset?: number) {
    let lineNumber = binarySearch(lineStarts, position, compareNumberValue, offset);
    if (lineNumber < 0) {
        lineNumber = ~lineNumber - 1;
    }
    return lineNumber;
}

export function computeLineAndCharacterOfLastLineEndPosition(lineStarts: readonly number[], position: number): TextPosition {
    let line = computeLineOfPosition(lineStarts, position);
    let character = position - lineStarts[line];
    if (lineStarts[line] > 0) {
        line--;
        character = lineStarts[line + 1] - 1 - lineStarts[line];
    }
    return {
        line,
        character,
    };
}

export function computeLineAndCharacterOfPosition(lineStarts: readonly number[], position: number): TextPosition {
    const line = computeLineOfPosition(lineStarts, position);
    return {
        line,
        character: position - lineStarts[line]
    };
}

export function computePositionOfLineAndCharacter(lineStarts: readonly number[], line: number, character: number): number {
    if (line < 0 || line >= lineStarts.length) {
        line = line < 0 ? 0 : lineStarts.length - 1;
    }
    return lineStarts[line] + character;
}

export function isLigalIdentifier(str: string): boolean {
    if (str.length === 0) {
        return false;
    }

    if (str.length === 1) {
        return isIdentifierStart(codePointAt(str, 0));
    }

    if (isIdentifierStart(codePointAt(str, 0))) {
        for (let i = 1; i < str.length; i++) {
            if (!isIdentifierPart(codePointAt(str, i))) {
                return false;
            }
        }
        return true;
    }

    return false;
}

// Test

export function isSymbolTable(obj?: any): obj is SymbolTable | ReadonlySymbolTable {
    return obj && hasOwnProperty.call(obj, "_symbolTableBrand");
}

export type NodeTestCallback = (node: Node | undefined) => boolean;

export function isPunctuationToken(flag: SyntaxKind): boolean {
    return flag >= SyntaxKind.openParenthesis && flag <= SyntaxKind.notEqual;
}

export function isModifierToken(flag: SyntaxKind): boolean {
    return flag === SyntaxKind.readonlyKeyword
        || flag === SyntaxKind.writeonlyKeyword
        || flag === SyntaxKind.optionKeyword
        || flag === SyntaxKind.defaultKeyword;
}

export function isUnaryOperatorToken(flag: SyntaxKind): boolean {
    return flag === SyntaxKind.notKeyword || flag === SyntaxKind.exclamation;
}

export function isDiagnosticMessage(obj: any): obj is DiagnosticMessage {
    return obj && hasOwnProperty.call(obj, "_diagnosicMessageBrand");
}

export function isNode(node: any): node is Node {
    return node !== undefined && hasOwnProperty.call(node, "flag");
}

export function isPrecedureCanExitToken(node: Node): node is Token<PrecedureCanExit> {
    if (node) {
        switch (node.kind) {
            case SyntaxKind.doKeyword:
            case SyntaxKind.forKeyword:
            case SyntaxKind.subKeyword:
            case SyntaxKind.functionKeyword:
                return true;
        }
    }
    return false;
}

export function isBinaryOperatorToken(flag: SyntaxKind): boolean {
    switch (flag) {
        case SyntaxKind.andKeyword:
        case SyntaxKind.orKeyword:
        case SyntaxKind.xorKeyword:
        case SyntaxKind.plus:
        case SyntaxKind.minus:
        case SyntaxKind.asterisk:
        case SyntaxKind.slash:
        case SyntaxKind.mod:
        case SyntaxKind.greater:
        case SyntaxKind.greaterEqual:
        case SyntaxKind.less:
        case SyntaxKind.lessEqual:
        case SyntaxKind.equal:
        case SyntaxKind.equalAsterisk:
        case SyntaxKind.equalEqual:
        case SyntaxKind.barbar:
        case SyntaxKind.ampersandAmpersand:
        case SyntaxKind.notEqual:
        case SyntaxKind.exclamationEqual:
        case SyntaxKind.likeKeyword:
        case SyntaxKind.isKeyword:
            return true;
    }
    return false;
}

export function isReadonlyArray<T>(obj: any): obj is ReadonlyArray<T> {
    return Array.isArray(obj);
}

export function isNodeArray<T extends Node>(array: any): array is NodeArray<T> {
    return Array.isArray(array) && array.hasOwnProperty("start") && array.hasOwnProperty("end");
}

export function isLiteralToken(flag: SyntaxKind): boolean {
    switch (flag) {
        case SyntaxKind.nullKeyword:
        case SyntaxKind.trueKeyword:
        case SyntaxKind.falseKeyword:
        case SyntaxKind.numberLiteral:
        case SyntaxKind.stringLiteral:
        case SyntaxKind.categoricalLiteral:
            return true;
    }
    return false;
}

export function isCategoricalLiteralEmpty(categorical: CategoricalLiteral): boolean {
    return categorical.categories.length === 0;
}

export function isSignatureToken(flag: SyntaxKind) {
    return flag === SyntaxKind.constSignature
        || flag === SyntaxKind.arrayTypeSignature
        || flag === SyntaxKind.parameterSignature
        || flag === SyntaxKind.propertySignature
        || flag === SyntaxKind.functionSignature
        || flag === SyntaxKind.interfaceSignature
        || flag === SyntaxKind.classSignature
        || flag === SyntaxKind.moduleSignature
        || flag === SyntaxKind.enumMemberSignature
        || flag === SyntaxKind.enumSignature;
}

export function isDeclarationToken(kind: SyntaxKind) {
    switch (kind) {
        case SyntaxKind.varDecl:
        case SyntaxKind.constDecl:
        case SyntaxKind.arrayDecl:
        case SyntaxKind.funcDecl:
        case SyntaxKind.sectionStat:
        case SyntaxKind.jobSection:
        case SyntaxKind.inputDataSourceSection:
        case SyntaxKind.outputDataSourceSection:
        case SyntaxKind.globalSQLVariablesSection:
        case SyntaxKind.metadataSection:
        case SyntaxKind.loggingSection:
        case SyntaxKind.eventSection:
        case SyntaxKind.location:
        case SyntaxKind.sourceFile:
        case SyntaxKind.mdmProperty:
        case SyntaxKind.mdmProperties:
        case SyntaxKind.mdmTemplate:
        case SyntaxKind.mdmTemplates:
        case SyntaxKind.mdmStyle:
        case SyntaxKind.mdmFontStyle:
        case SyntaxKind.mdmControlStyle:
        case SyntaxKind.mdmCellStyle:
        case SyntaxKind.mdmClass:
        case SyntaxKind.mdmField:
        case SyntaxKind.mdmHierarchicalView:
        case SyntaxKind.mdmAreaName:
        case SyntaxKind.mdmCategory:
        case SyntaxKind.mdmCategories:
        case SyntaxKind.mdmSublist:
        case SyntaxKind.mdmOther:
        case SyntaxKind.mdmMultiplier:
        case SyntaxKind.mdmCategoryExpression:
        case SyntaxKind.mdmElementType:
        case SyntaxKind.mdmKeycode:
        case SyntaxKind.mdmFactor:
        case SyntaxKind.mdmHelperFields:
        case SyntaxKind.mdmUsageType:
            return true;
        default:
            return false;
    }
}

export function isPreprocessorToken(kind: SyntaxKind) {
    switch (kind) {
        case SyntaxKind.ppDefine:
        case SyntaxKind.ppUndef:
        case SyntaxKind.ppIf:
        case SyntaxKind.ppInclude:
        case SyntaxKind.ppError:
        case SyntaxKind.ppLine:
            return true;
        default:
            return false;
    }
}

export function isMetadataFieldToken(kind: SyntaxKind) {
    switch (kind) {
        case SyntaxKind.loopKeyword:
        case SyntaxKind.mdmLongKeyword:
        case SyntaxKind.mdmDoubleKeyword:
        case SyntaxKind.mdmTextKeyword:
        case SyntaxKind.mdmDateKeyword:
        case SyntaxKind.mdmBooleanKeyword:
        case SyntaxKind.mdmCategoricalKeyword:
        case SyntaxKind.mdmInfoKeyword:
        case SyntaxKind.mdmDefineKeyword:
        case SyntaxKind.mdmGridKeyword:
        case SyntaxKind.mdmCompoundKeyword:
        case SyntaxKind.mdmBlockKeyword:
        case SyntaxKind.mdmPageKeyword:
            return true;
        default:
            return false;
    }
}

export function isKeyWordToken(node: Node | undefined): node is KeywordToken<KeywordTokenKind> {
    return node !== undefined && node.kind >= SyntaxKind.firstKeyword && node.kind <= SyntaxKind.lastKeyword;
}

export function isMissingNodeArray(nodeArray: NodeArray<Node>): boolean {
    return !!(nodeArray as MissingNodeArray<Node>).isMissing;
}

export function isSymbol(s: any): s is Symbol {
    return s !== undefined && hasOwnProperty.call(s, "flag") && hasOwnProperty.call(s, "checkFlag");
}

//

export function isPreprocessorOperatorToken(flag: SyntaxKind): boolean {
    return flag >= SyntaxKind.firstPPOperator && flag <= SyntaxKind.lastPPOperator;
}

export function getObjectTypeFlag(type: Type): ObjectTypeFlag {
    return type.flag === TypeFlag.object ? (type as ObjectType).objectTypeFlag : ObjectTypeFlag.null;
}

export function forEachSourceFileInclude(source: SourceFile, callback: (s: SourceFile, p: SourceFile) => void) {
    for (const s of source.references) {
        callback(s, source);
        forEachSourceFileInclude(s, callback);
    }
}

//

export function getOperatorPrecedence(flag: UnaryOperatorKind | BinaryOperatorKind): number {
    switch (flag) {
        case SyntaxKind.andKeyword:
        case SyntaxKind.orKeyword:
        case SyntaxKind.xorKeyword:
        case SyntaxKind.barbar:
        case SyntaxKind.ampersandAmpersand:
            return 1;

        case SyntaxKind.equal:
        case SyntaxKind.notEqual:
        case SyntaxKind.less:
        case SyntaxKind.lessEqual:
        case SyntaxKind.greater:
        case SyntaxKind.greaterEqual:
        case SyntaxKind.equalAsterisk:
        case SyntaxKind.exclamationEqual:
        case SyntaxKind.equalEqual:
            return 2;

        case SyntaxKind.plus:
        case SyntaxKind.minus:
        case SyntaxKind.likeKeyword:
        case SyntaxKind.isKeyword:
            return 3;

        case SyntaxKind.asterisk:
        case SyntaxKind.slash:
        case SyntaxKind.mod:
            return 4;

        case SyntaxKind.notKeyword:
        case SyntaxKind.exclamation:
            return 5;
    }
}

// Event Section Types
const sectionFlag: MapLike<SectionKind> = {
    job:                  SectionKind.job,
    inputdatasource:      SectionKind.inputDataSource,
    outputdatasource:     SectionKind.outputDataSource,
    globalsqlvariables:   SectionKind.globalSQLVariables,
    metadata:             SectionKind.metadata,
    logging:              SectionKind.logging,
    event:                SectionKind.event,
    routing:              SectionKind.routing,
};

const sectionFlagObject = new Map(getMapEntries(sectionFlag));

export function getSectionFlag(text: string): SectionKind {
    return sectionFlagObject.get(text.toLowerCase()) || SectionKind.none;
}

// Event Section Names
const eventSectionName: MapLike<EventSectionKind> = {
    onbeforejobstart:                  EventSectionKind.onBeforeJobStart,
    onaftermetadatatransformation:     EventSectionKind.onAfterMetaDataTransformation,
    onjobstart:                        EventSectionKind.onJobStart,
    onnextcase:                        EventSectionKind.onNextCase,
    onbadcase:                         EventSectionKind.onBadCase,
    onjobend:                          EventSectionKind.onJobEnd,
    onafterjobend:                     EventSectionKind.onAfterJobEnd,
};

const eventSectionNameObject = new Map(getMapEntries(eventSectionName));

export function getEventSectionFlag(text: string): EventSectionKind {
    return eventSectionNameObject.get(text.toLowerCase()) || EventSectionKind.none;
}


const textToMrsKeywordObject: MapLike<KeywordTokenKind> = {
    and: SyntaxKind.andKeyword,
    case: SyntaxKind.caseKeyword,
    const: SyntaxKind.constKeyword,
    dim: SyntaxKind.dimKeyword,
    do: SyntaxKind.doKeyword,
    each: SyntaxKind.eachKeyword,
    else: SyntaxKind.elseKeyword,
    elseif: SyntaxKind.elseifKeyword,
    end: SyntaxKind.endKeyword,
    error: SyntaxKind.errorKeyword,
    exit: SyntaxKind.exitKeyword,
    explicit: SyntaxKind.explicitKeyword,
    false: SyntaxKind.falseKeyword,
    for: SyntaxKind.forKeyword,
    function: SyntaxKind.functionKeyword,
    globalvariables: SyntaxKind.globalVariablesKeyword,
    goto: SyntaxKind.gotoKeyword,
    if: SyntaxKind.ifKeyword,
    implicit: SyntaxKind.implicitKeyword,
    in: SyntaxKind.inKeyword,
    is: SyntaxKind.isKeyword,
    like: SyntaxKind.likeKeyword,
    loop: SyntaxKind.loopKeyword,
    mod: SyntaxKind.mod,
    next: SyntaxKind.nextKeyword,
    not: SyntaxKind.notKeyword,
    null: SyntaxKind.nullKeyword,
    on: SyntaxKind.onKeyword,
    option: SyntaxKind.optionKeyword,
    or: SyntaxKind.orKeyword,
    paper: SyntaxKind.paper,
    resume: SyntaxKind.resumeKeyword,
    section: SyntaxKind.sectionKeyword,
    select: SyntaxKind.selectKeyword,
    set: SyntaxKind.setKeyword,
    step: SyntaxKind.stepKeyword,
    sub: SyntaxKind.subKeyword,
    then: SyntaxKind.thenKeyword,
    to: SyntaxKind.toKeyword,
    true: SyntaxKind.trueKeyword,
    until: SyntaxKind.untilKeyword,
    while: SyntaxKind.whileKeyword,
    with: SyntaxKind.withKeyword,
    xor: SyntaxKind.xorKeyword
};

const textToDeclareKeywordObject: MapLike<DelcareKeywordKind> = {
    as: SyntaxKind.asKeyword,
    module: SyntaxKind.moduleKeyword,
    interface: SyntaxKind.interfaceKeyword,
    class: SyntaxKind.classKeyword,
    enum: SyntaxKind.enumKeyword,
    implements: SyntaxKind.implementsKeyword,
    inherits: SyntaxKind.inheritsKeyword,
    paramarray: SyntaxKind.paramArrayKeyword,
    property: SyntaxKind.propertyKeyword,
    readonly: SyntaxKind.readonlyKeyword,
    writeonly: SyntaxKind.writeonlyKeyword,
    optional: SyntaxKind.optionalKeyword,
    default: SyntaxKind.defaultKeyword,
};

const textToDmsKeywordObject: MapLike<DmsSectionKeywordKind> = {
    job:                SyntaxKind.jobKeyword,
    inputdatasource:    SyntaxKind.inputDataSourceKeyword,
    outputdatasource:   SyntaxKind.outputDataSourceKeyword,
    globalsqlvariables: SyntaxKind.globalSQLVariablesKeyword,
    metadata:           SyntaxKind.metadataKeyword,
    logging:            SyntaxKind.loggingKeyword,
    event:              SyntaxKind.eventKeyword,
    routing:            SyntaxKind.routingKeyword,
};

const textToMetadataKeywordObject: MapLike<MDMKeywordKind> = {
    style: SyntaxKind.mdmStyleKeyword,
    labelstyle: SyntaxKind.mdmLabelStyleKeyword,
    templates: SyntaxKind.mdmTemplatesKeyword,
    long: SyntaxKind.mdmLongKeyword,
    double: SyntaxKind.mdmDoubleKeyword,
    text: SyntaxKind.mdmTextKeyword,
    date: SyntaxKind.mdmDateKeyword,
    boolean: SyntaxKind.mdmBooleanKeyword,
    categorical: SyntaxKind.mdmCategoricalKeyword,
    define: SyntaxKind.mdmDefineKeyword,
    info: SyntaxKind.mdmInfoKeyword,
    compound: SyntaxKind.mdmCompoundKeyword,
    block: SyntaxKind.mdmBlockKeyword,
    page: SyntaxKind.mdmPageKeyword,
    db: SyntaxKind.mdmDBKeyword,
    codes: SyntaxKind.mdmCodesKeyword,
    expression: SyntaxKind.mdmExpressionKeyword,
    deriveelements: SyntaxKind.mdmDeriveElementsKeyword,
    noderiveelements: SyntaxKind.mdmNoDeriveElementsKeyword,
    validation: SyntaxKind.mdmValidationKeyword,
    initialanswer: SyntaxKind.mdmInitialAnswerKeyword,
    defaultanswer: SyntaxKind.mdmDefaultAnswerKeyword,
    nocasedata: SyntaxKind.mdmNocaseDataKeyword,
    unversioned: SyntaxKind.mdmUnversionedKeyword,
    axis: SyntaxKind.mdmAxisKeyword,
    usagetype: SyntaxKind.mdmUsageTypeKeyword,
    helperfields: SyntaxKind.mdmHelperFieldsKeyword,
    precision: SyntaxKind.mdmPrecisionKeyword,
    rotate: SyntaxKind.mdmRotateKeyword,
    rot: SyntaxKind.mdmRotKeyword,
    randomize: SyntaxKind.mdmRandomizeKeyword,
    ran: SyntaxKind.mdmRanKeyword,
    reverse: SyntaxKind.mdmReverseKeyword,
    rev: SyntaxKind.mdmRevKeyword,
    ascending: SyntaxKind.mdmAscendingKeyword,
    asc: SyntaxKind.mdmAscKeyword,
    descending: SyntaxKind.mdmDescendingKeyword,
    desc: SyntaxKind.mdmDescKeyword,
    namespace: SyntaxKind.mdmNamespaceKeyword,
    use: SyntaxKind.mdmUseKeyword,
    sublist: SyntaxKind.mdmSublistKeyword,
    exclusive: SyntaxKind.mdmExclusiveKeyword,
    factor: SyntaxKind.mdmFactorKeyword,
    keycode: SyntaxKind.mdmKeycodeKeyword,
    fix: SyntaxKind.mdmFixKeyword,
    canfilter: SyntaxKind.mdmCanFilterKeyword,
    nofilter: SyntaxKind.mdmNoFilterKeyword,
    other: SyntaxKind.mdmOtherKeyword,
    multiplier: SyntaxKind.mdmMultiplierKeyword,
    elementtype: SyntaxKind.mdmElementTypeKeyword,
    dk: SyntaxKind.mdmDKKeyword,
    ref: SyntaxKind.mdmREFKeyword,
    na: SyntaxKind.mdmNAKeyword,
    fields: SyntaxKind.mdmFieldsKeyword,
    row: SyntaxKind.mdmRowKeyword,
    column: SyntaxKind.mdmColumnKeyword,
    expand: SyntaxKind.mdmExpandKeyword,
    noexpand: SyntaxKind.mdmNoExpandKeyword,
    grid: SyntaxKind.mdmGridKeyword,
    inline: SyntaxKind.mdmInlineKeyword,
    lcl: SyntaxKind.mdmLCLKeyword,
    scale: SyntaxKind.mdmScaleKeyword,
};

const textToPreprocessorKeywordObject: MapLike<PPKeywordKind> = {
    "include": SyntaxKind.ppIncludeKeyword,
    "define": SyntaxKind.ppDefineKeyword,
    "if": SyntaxKind.ppIfKeyword,
    "ifdef": SyntaxKind.ppIfDefKeyword,
    "ifndef": SyntaxKind.ppUndefKeyword,
    "elif": SyntaxKind.ppElIfKeyword,
    "else": SyntaxKind.ppElseKeyword,
    "endif": SyntaxKind.ppEndIfKeyword,
    "error": SyntaxKind.ppErrorKeyword,
    "undef": SyntaxKind.ppUndefKeyword,
    "line": SyntaxKind.ppLineKeyword,
};

const textToAllKeywordObject: MapLike<KeywordTokenKind | DelcareKeywordKind | DmsSectionKeywordKind | MDMKeywordKind> = {
    ...textToDeclareKeywordObject,
    ...textToMrsKeywordObject,
    ...textToDmsKeywordObject,
    ...textToMetadataKeywordObject,
};

const textToPunctuationTokenObject: MapLike<SyntaxKind> = {
    "(": SyntaxKind.openParenthesis,
    ")": SyntaxKind.closeParenthesis,
    "[": SyntaxKind.openBracket,
    "]": SyntaxKind.closeBracket,
    "{": SyntaxKind.openCurly,
    "}": SyntaxKind.closeCurly,
    ".": SyntaxKind.dot,
    "..": SyntaxKind.dotDot,
    ":": SyntaxKind.colon,
    ";": SyntaxKind.semicolon,
    ",": SyntaxKind.comma,
    "^": SyntaxKind.caret,
    "=": SyntaxKind.equal,
    "+": SyntaxKind.plus,
    "-": SyntaxKind.minus,
    "*": SyntaxKind.asterisk,
    "/": SyntaxKind.slash,
    "\\": SyntaxKind.backSlash,
    ">": SyntaxKind.greater,
    ">=": SyntaxKind.greaterEqual,
    "<": SyntaxKind.less,
    "<=": SyntaxKind.lessEqual,
    "<>": SyntaxKind.notEqual,
    "=*": SyntaxKind.equalAsterisk,
    "\"": SyntaxKind.quotation,
    "'": SyntaxKind.apostrophe,
    "&": SyntaxKind.ampersand,
    "&&": SyntaxKind.ampersandAmpersand,
    "||": SyntaxKind.barbar,
    "!": SyntaxKind.exclamation,
    "!=": SyntaxKind.exclamationEqual,
};

const textToTokenObject: MapLike<SyntaxKind> = {
    ...textToAllKeywordObject,
    ...textToPunctuationTokenObject
};

const textToMrsKeyword = new Map(getMapEntries(textToMrsKeywordObject));
const textToDeclareKeyword = new Map(getMapEntries(textToDeclareKeywordObject));
const textToDmsKeyword = new Map(getMapEntries(textToDmsKeywordObject));
const textToMetadataKeyword = new Map(getMapEntries(textToMetadataKeywordObject));
const textToPunctuationToken = new Map(getMapEntries(textToPunctuationTokenObject));
const textToToken = new Map(getMapEntries(textToTokenObject));
const textToPreprocessorKeyword = new Map(getMapEntries(textToPreprocessorKeywordObject));

export function normalizeLineFeedCharacter(text: string) {
    let result = text.replace(/(_|\\)\r?\n/g, "");
    if (result.startsWith("#")) {
        result = result.replace(/(?<=#)\s+/g, "");
    }
    return result;
}

export function stringToMrsKeyword(str: string): KeywordTokenKind | undefined {
    return textToMrsKeyword.get(normalizeLineFeedCharacter(str.toLowerCase()));
}

export function stringToDeclareKeyword(str: string): DelcareKeywordKind | undefined {
    return textToDeclareKeyword.get(normalizeLineFeedCharacter(str.toLowerCase()));
}

export function stringToDmsSectionKeyword(str: string): DmsSectionKeywordKind | undefined {
    return textToDmsKeyword.get(normalizeLineFeedCharacter(str.toLowerCase()));
}

export function stringToMetadataKeyword(str: string): MDMKeywordKind | undefined {
    return textToMetadataKeyword.get(normalizeLineFeedCharacter(str.toLowerCase()));
}

// 预处理关键字区分大小写，必须小写
export function stringToPreprocessorKeyword(str: string): SyntaxKind | undefined {
    return textToPreprocessorKeyword.get(str);
}

export function stringToPunctuationToken(str: string): SyntaxKind | undefined {
    return textToPunctuationToken.get(normalizeLineFeedCharacter(str.toLowerCase()));
}

export function stringToToken(str: string): SyntaxKind | undefined {
    return textToToken.get(normalizeLineFeedCharacter(str.toLowerCase()));
}

function makeReservedMap(...sources: Map<string, number>[]): string[] {
    const result: string[] = [];
    for (const source of sources) {
        source.forEach((value, name) => {
            result[value] = name;
        });
    }
    return result;
}

const tokenToText = makeReservedMap(textToToken, textToPreprocessorKeyword, textToMetadataKeyword, textToDmsKeyword, textToPunctuationToken);

export function tokenToString(flag: SyntaxKind): string {
    return tokenToText[flag];
}
const textToEventSectionFlag: MapLike<EventSectionKind> = {
    onbeforejobstart               : EventSectionKind.onBeforeJobStart,
    onaftermetadatatransformation  : EventSectionKind.onAfterMetaDataTransformation,
    onjobstart                     : EventSectionKind.onJobStart,
    onnextcase                     : EventSectionKind.onNextCase,
    onbadcase                      : EventSectionKind.onBadCase,
    onjobend                       : EventSectionKind.onJobEnd,
    onafterjobend                  : EventSectionKind.onAfterJobEnd,
};

const textToEventSectionFlagObject = new Map(getMapEntries(textToEventSectionFlag));

export function stringToEventSectionFlag(name: string): EventSectionKind | undefined {
    return textToEventSectionFlagObject.get(name.toLowerCase());
}

const textToUserContextObject: MapLike<MDMUserContextFlags> = {
    analysis: MDMUserContextFlags.analysis,
    question: MDMUserContextFlags.question,
    qc: MDMUserContextFlags.qc,
    paper: MDMUserContextFlags.paper,
    cardcol: MDMUserContextFlags.cardcol,
    sav: MDMUserContextFlags.sav,
    webapp: MDMUserContextFlags.webapp,
    web: MDMUserContextFlags.web,
    cati: MDMUserContextFlags.cati,
    mobile: MDMUserContextFlags.mobile,
    papi: MDMUserContextFlags.papi,
};

const textToUserContext = new Map(getMapEntries(textToUserContextObject));

export function stringToUserContext(str: string): MDMUserContextFlags | undefined {
    return textToUserContext.get(normalizeLineFeedCharacter(str.toLowerCase()));
}

const textToLabelTypeObject: MapLike<MDMLabelTypeFlags> = {
    label: MDMLabelTypeFlags.label,
    instruction: MDMLabelTypeFlags.instruction,
    shortname: MDMLabelTypeFlags.shortName,
};

const textToLabelType = new Map(getMapEntries(textToLabelTypeObject));

export function stringToLabelType(str: string): MDMLabelTypeFlags | undefined {
    return textToLabelType.get(normalizeLineFeedCharacter(str.toLowerCase()));
}

const textToMetadataStylePropertyFlagObject: MapLike<MDMPropertyFlags> = {
    align: MDMPropertyFlags.align,
    bgcolor: MDMPropertyFlags.bgColor,
    cell: MDMPropertyFlags.cell,
    colors: MDMPropertyFlags.color,
    columns: MDMPropertyFlags.columns,
    control: MDMPropertyFlags.control,
    cursor: MDMPropertyFlags.cursor,
    elementalign: MDMPropertyFlags.elementAlign,
    font: MDMPropertyFlags.font,
    height: MDMPropertyFlags.height,
    hidden: MDMPropertyFlags.hidden,
    image: MDMPropertyFlags.image,
    imageposition: MDMPropertyFlags.imagePosition,
    indent: MDMPropertyFlags.indent,
    orientation: MDMPropertyFlags.orientation,
    rows: MDMPropertyFlags.rows,
    verticalalign: MDMPropertyFlags.verticalAlign,
    width: MDMPropertyFlags.width,
    zindex: MDMPropertyFlags.zIndex,
};

const textToMetadataStylePropertyFlag = new Map(getMapEntries(textToMetadataStylePropertyFlagObject));

export function stringToMetadataStylePropertyFlag(str: string): MDMPropertyFlags | undefined {
    return textToMetadataStylePropertyFlag.get(normalizeLineFeedCharacter(str.toLowerCase()));
}

const textToMetadataCellStylePropertyFlagObject: MapLike<MDMCellStylePropertyFlags> = {
    bgcolor: MDMCellStylePropertyFlags.bgColor,
    borderbottomcolor: MDMCellStylePropertyFlags.borderBottomColor,
    borderbottomstyle: MDMCellStylePropertyFlags.borderBottomStyle,
    borderbottomwidth: MDMCellStylePropertyFlags.borderBottomWidth,
    bordercolor: MDMCellStylePropertyFlags.borderColor,
    borderleftcolor: MDMCellStylePropertyFlags.borderLeftColor,
    borderleftstyle: MDMCellStylePropertyFlags.borderLeftStyle,
    borderleftwidth: MDMCellStylePropertyFlags.borderLeftWidth,
    borderrightcolor: MDMCellStylePropertyFlags.borderRightColor,
    borderrightstyle: MDMCellStylePropertyFlags.borderRightStyle,
    borderrightwidth: MDMCellStylePropertyFlags.borderRightWidth,
    borderstyle: MDMCellStylePropertyFlags.borderStyle,
    bordertopcolor: MDMCellStylePropertyFlags.borderTopColor,
    bordertopstyle: MDMCellStylePropertyFlags.borderTopStyle,
    bordertopwidth: MDMCellStylePropertyFlags.borderTopWidth,
    borderwidth: MDMCellStylePropertyFlags.borderWidth,
    colspan: MDMCellStylePropertyFlags.colspan,
    height: MDMCellStylePropertyFlags.height,
    padding: MDMCellStylePropertyFlags.padding,
    paddingbottom: MDMCellStylePropertyFlags.paddingBottom,
    paddingleft: MDMCellStylePropertyFlags.paddingLeft,
    paddingright: MDMCellStylePropertyFlags.paddingRight,
    paddingtop: MDMCellStylePropertyFlags.paddingTop,
    repeatheader: MDMCellStylePropertyFlags.repeatHeader,
    repeatsideheader: MDMCellStylePropertyFlags.repeatSideHeader,
    rowspan: MDMCellStylePropertyFlags.rowspan,
    width: MDMCellStylePropertyFlags.width,
    wrap: MDMCellStylePropertyFlags.wrap,
};

const textToMetadataCellStylePropertyFlag = new Map(getMapEntries(textToMetadataCellStylePropertyFlagObject));

export function stringToMetadataCellStylePropertyFlag(str: string): MDMCellStylePropertyFlags | undefined {
    return textToMetadataCellStylePropertyFlag.get(normalizeLineFeedCharacter(str.toLowerCase()).trim());
}

const textToMetadataControlStylePropertyFlagObject: MapLike<MDMControlStylePropertyFlags> = {
    accelerator: MDMControlStylePropertyFlags.accelerator,
    readonly: MDMControlStylePropertyFlags.readonly,
    type: MDMControlStylePropertyFlags.type,
};

const textToMetadataControlStylePropertyFlag = new Map(getMapEntries(textToMetadataControlStylePropertyFlagObject));

export function stringToMetadataControlStylePropertyFlag(str: string): MDMControlStylePropertyFlags | undefined {
    return textToMetadataControlStylePropertyFlag.get(normalizeLineFeedCharacter(str.toLowerCase()).trim());
}

// Font Style

const textToMetadataFontStylePropertyFlagObject: MapLike<MDMFontStylePropertyFlags> = {
    family: MDMFontStylePropertyFlags.family,
    isblink: MDMFontStylePropertyFlags.isBlink,
    isbold: MDMFontStylePropertyFlags.isBold,
    isitalic: MDMFontStylePropertyFlags.isItalic,
    isoverline: MDMFontStylePropertyFlags.isOverline,
    isstrikethrough: MDMFontStylePropertyFlags.isStrikeThrough,
    issubscript: MDMFontStylePropertyFlags.isSubscript,
    issuperscript: MDMFontStylePropertyFlags.isSuperscript,
    isunderline: MDMFontStylePropertyFlags.isUnderline,
    size: MDMFontStylePropertyFlags.size,
};

const textToMetadataFontStylePropertyFlag = new Map(getMapEntries(textToMetadataFontStylePropertyFlagObject));

export function stringToMetadataFontStylePropertyFlag(str: string): MDMFontStylePropertyFlags | undefined {
    return textToMetadataFontStylePropertyFlag.get(normalizeLineFeedCharacter(str.toLowerCase()));
}

// Test Property Valuse

const styleEnumeratorValues = {
    borderStyles: new Map(getObjectArrayMapEntries([
        "Double",
        "Grove",
        "Inset",
        "None",
        "Outset",
        "Ridge",
        "Solid"
    ], e => e.toLowerCase())),
    // Button, CheckButton, ComboList (reserved for future use), Date, DateTime, DropList, Edit, ListBox, ListControl, MultiLineEdit, Password, RadioButton, SingleLineEdit, Static, or Time.
    control: new Map(getObjectArrayMapEntries([
        "Button",
        "CheckButton",
        "ComboList",
        "Date",
        "DateTime",
        "DropList",
        "Edit",
        "ListBox",
        "ListControl",
        "MultiLineEdit",
        "Password",
        "RadioButton",
        "SingleLineEdit",
        "Static",
        "Time",
    ], e => e.toLowerCase())),
    // Align	Enumeration	Center, Default, Justify, Left, or Right.
    horizonAlign: new Map(getObjectArrayMapEntries([
        "Center",
        "Default",
        "Justify",
        "Left",
        "Right"
    ], e => e.toLowerCase())),
    // Cursor	Enumeration	Auto, CrossHair, Default, Pointer, Move, EResize, NEResize, NResize, NWResize, WResize, SWResize, SResize, SEResize, Text, Wait, or Help.
    cursor: new Map(getObjectArrayMapEntries([
        "Auto",
        "CrossHair",
        "Default",
        "Pointer",
        "Move",
        "EResize",
        "NEResize",
        "NResize",
        "NWResize",
        "WResize",
        "SWResize",
        "SResize",
        "SEResize",
        "Text",
        "Wait",
        "Help"
    ], e => e.toLowerCase())),
    // ElementAlign	Enumeration	Default, NewLine, or Right.
    elementAlign: new Map(getObjectArrayMapEntries([
        "Default",
        "NewLine",
        "Right"
    ], e => e.toLowerCase())),
    // ImagePosition	Enumeration	Bottom, ImageOnly, Left, None, Right, or Top.
    imagePosition: new Map(getObjectArrayMapEntries([
        "Bottom",
        "ImageOnly",
        "Left",
        "None",
        "Right",
        "Top",
    ], e => e.toLowerCase())),
    // Orientation	Enumeration	Column, Default, or Row.
    orientation: new Map(getObjectArrayMapEntries([
        "Column",
        "Default",
        "Row",
    ], e => e.toLowerCase())),
    // VerticalAlign	Enumeration	Baseline, Bottom, Default, Middle, Sub, Super, TextBottom, TextTop, or Top.
    verticalAlign: new Map(getObjectArrayMapEntries([
        "Baseline",
        "Bottom",
        "Default",
        "Middle",
        "Sub",
        "Super",
        "TextBottom",
        "TextTop",
        "Top",
    ], e => e.toLowerCase())),
};

/**
 * 检查配置的单元格样式值是否符合要求
 * @param node 值节点
 * @param flag 单元格样式配置类型
 * @returns 值是否符合要求
 */
export function testCellStylePropertyValue(node: Node, flag: MDMCellStylePropertyFlags): boolean {
    switch (flag) {

        case MDMCellStylePropertyFlags.bgColor:
        case MDMCellStylePropertyFlags.borderBottomColor:
        case MDMCellStylePropertyFlags.borderColor:
        case MDMCellStylePropertyFlags.borderLeftColor:
        case MDMCellStylePropertyFlags.borderRightColor:
        case MDMCellStylePropertyFlags.borderTopColor:
            return node.isIdentifier() || node.isStringLiteral();

        case MDMCellStylePropertyFlags.height:
        case MDMCellStylePropertyFlags.width:
            return node.isNumberLiteral() || (node.isStringLiteral() && stringIsCorrectLength(node.text));

        case MDMCellStylePropertyFlags.borderBottomStyle:
        case MDMCellStylePropertyFlags.borderLeftStyle:
        case MDMCellStylePropertyFlags.borderStyle:
        case MDMCellStylePropertyFlags.borderTopStyle:
        case MDMCellStylePropertyFlags.borderRightStyle:
            return (node.isIdentifier() || node.isStringLiteral()) && styleEnumeratorValues.borderStyles.get(node.text.toLowerCase().trim()) !== undefined;

        // 	A positive integer.
        case MDMCellStylePropertyFlags.borderBottomWidth:
        case MDMCellStylePropertyFlags.borderLeftWidth:
        case MDMCellStylePropertyFlags.borderRightWidth:
        case MDMCellStylePropertyFlags.borderTopWidth:
        case MDMCellStylePropertyFlags.borderWidth:
        case MDMCellStylePropertyFlags.colspan:
        case MDMCellStylePropertyFlags.padding:
        case MDMCellStylePropertyFlags.paddingBottom:
        case MDMCellStylePropertyFlags.paddingLeft:
        case MDMCellStylePropertyFlags.paddingRight:
        case MDMCellStylePropertyFlags.paddingTop:
        case MDMCellStylePropertyFlags.rowspan:
            return node.isNumberLiteral() || (node.isStringLiteral() && parseInt(node.text) > 0);

        // A positive integer or zero.
        case MDMCellStylePropertyFlags.repeatHeader:
        case MDMCellStylePropertyFlags.repeatSideHeader:
            return (node.isNumberLiteral() && node.value > 0) || (node.isStringLiteral() && parseInt(node.text, 10) >= 0);

        // True or False.
        case MDMCellStylePropertyFlags.wrap:
            return node.isBooleanLiteral() || (node.isStringLiteral() && stringIsBoolean(node.text));

    }
}

/**
 * 检查配置的控件样式的值类型是否正确
 * @param node 值节点，即'='右侧的值
 * @param flag 属性类型
 * @returns 值类型是否正确
 */
export function testControlStylePropertyValue(node: Node, flag: MDMControlStylePropertyFlags): boolean {
    switch (flag) {
        case MDMControlStylePropertyFlags.accelerator:
            return node.isStringLiteral() || node.isIdentifier();
        case MDMControlStylePropertyFlags.readonly:
            return node.isBooleanLiteral() || (node.isStringLiteral() && stringIsBoolean(node.text));
        case MDMControlStylePropertyFlags.type:
            return (node.isIdentifier() || node.isStringLiteral()) && styleEnumeratorValues.control.get(node.text.toLowerCase().trim()) !== undefined;
    }
}

// Font Style
// check property value type
// Family is the default child property

/**
 * 判断配置的字体样式属性值类型是否正确
 * @param valueNode 属性值节点
 * @param flag 属性类型
 * @returns 属性值类型是否正确
 */
export function testFontStylePropertyValue(valueNode: Node, flag: MDMFontStylePropertyFlags): boolean {
    switch (flag) {
        case MDMFontStylePropertyFlags.family:
            return valueNode.isStringLiteral();
        case MDMFontStylePropertyFlags.isBlink:
        case MDMFontStylePropertyFlags.isBold:
        case MDMFontStylePropertyFlags.isItalic:
        case MDMFontStylePropertyFlags.isOverline:
        case MDMFontStylePropertyFlags.isStrikeThrough:
        case MDMFontStylePropertyFlags.isSubscript:
        case MDMFontStylePropertyFlags.isSuperscript:
        case MDMFontStylePropertyFlags.isUnderline:
            return valueNode.isBooleanLiteral();
        case MDMFontStylePropertyFlags.size:
            return (valueNode.isNumberLiteral() && !valueNode.isFloat) || (valueNode.isStringLiteral() && parseInt(valueNode.text) > 0);
    }
}


export function testStylePropertyValue(valueNode: Node, flag: MDMPropertyFlags): boolean {
    switch (flag) {
        // Enumerators
        case MDMPropertyFlags.align:
            return (valueNode.isStringLiteral() || valueNode.isIdentifier()) && styleEnumeratorValues.horizonAlign.get(valueNode.text.toLowerCase().trim()) !== undefined;
        case MDMPropertyFlags.cursor:
            return (valueNode.isStringLiteral() || valueNode.isIdentifier()) && styleEnumeratorValues.cursor.get(valueNode.text.toLowerCase().trim()) !== undefined;
        case MDMPropertyFlags.elementAlign:
            return (valueNode.isStringLiteral() || valueNode.isIdentifier()) && styleEnumeratorValues.elementAlign.get(valueNode.text.toLowerCase().trim()) !== undefined;
        case MDMPropertyFlags.imagePosition:
            return (valueNode.isStringLiteral() || valueNode.isIdentifier()) && styleEnumeratorValues.imagePosition.get(valueNode.text.toLowerCase().trim()) !== undefined;
        case MDMPropertyFlags.orientation:
            return (valueNode.isStringLiteral() || valueNode.isIdentifier()) && styleEnumeratorValues.orientation.get(valueNode.text.toLowerCase().trim()) !== undefined;
        case MDMPropertyFlags.verticalAlign:
            return (valueNode.isStringLiteral() || valueNode.isIdentifier()) && styleEnumeratorValues.verticalAlign.get(valueNode.text.toLowerCase().trim()) !== undefined;

        // Boolean
        case MDMPropertyFlags.hidden:
            return valueNode.isBooleanLiteral() || (valueNode.isStringLiteral() && stringIsBoolean(valueNode.text));

        // String
        case MDMPropertyFlags.bgColor:
        case MDMPropertyFlags.color:
        case MDMPropertyFlags.image:
            return valueNode.isStringLiteral() || valueNode.isIdentifier();
        case MDMPropertyFlags.width:
        case MDMPropertyFlags.height:
            return (valueNode.isStringLiteral() && stringIsCorrectLength(valueNode.text)) || valueNode.isNumberLiteral();

        // Number
        case MDMPropertyFlags.columns:
        case MDMPropertyFlags.indent:
        case MDMPropertyFlags.rows:
        case MDMPropertyFlags.zIndex:
            return valueNode.isNumberLiteral() || (valueNode.isStringLiteral() && stringIsInteger(valueNode.text));

        // Cell / Font / Control 跳过
        case MDMPropertyFlags.cell:
        case MDMPropertyFlags.font:
        case MDMPropertyFlags.control:
            return true;
    }
}

const textToMetadataUsageTypeFlagObject: MapLike<MDMUsageTypeFlags> = {
    filter: MDMUsageTypeFlags.filter,
    weight: MDMUsageTypeFlags.weight,
    multiplier: MDMUsageTypeFlags.multiplier,
    coding: MDMUsageTypeFlags.coding,
    sourcefile: MDMUsageTypeFlags.sourceFile,
    otherspecify: MDMUsageTypeFlags.otherSpecify,
    helperfield: MDMUsageTypeFlags.helperField,
};

const textToMetadataUsageTypeFlag = new Map(getMapEntries(textToMetadataUsageTypeFlagObject));

export function stringToMetadataUsageTypeFlag(str: string): MDMUsageTypeFlags | undefined {
    return textToMetadataUsageTypeFlag.get(normalizeLineFeedCharacter(str.toLowerCase()));
}

const textToMetadataElementTypeFlagObject: MapLike<MDMCategoryElementTypeFlags> = {
    analysisbase: MDMCategoryElementTypeFlags.analysisBase,
    analysiscategory: MDMCategoryElementTypeFlags.analysisCategory,
    analysismaximum: MDMCategoryElementTypeFlags.analysisMaximum,
    analysismean: MDMCategoryElementTypeFlags.analysisMean,
    analysisminimum: MDMCategoryElementTypeFlags.analysisMinimum,
    analysissamplevariance: MDMCategoryElementTypeFlags.analysisSampleVariance,
    analysisstddev: MDMCategoryElementTypeFlags.analysisStdDev,
    analysisstderr: MDMCategoryElementTypeFlags.analysisStdErr,
    analysissubheading: MDMCategoryElementTypeFlags.analysisSubHeading,
    analysissubtotal: MDMCategoryElementTypeFlags.analysisSubTotal,
    analysissummarydata: MDMCategoryElementTypeFlags.analysisSummaryData,
    analysistotal: MDMCategoryElementTypeFlags.analysisTotal,
};

const textToMetadataElementTypeFlag = new Map(getMapEntries(textToMetadataElementTypeFlagObject));

export function stringToMetadataElementTypeFlag(str: string): MDMCategoryElementTypeFlags | undefined {
    return textToMetadataElementTypeFlag.get(normalizeLineFeedCharacter(str.toLowerCase()));
}

const textToMetadataDatabaseQuestionsColumnProperty = new Map(getObjectArrayMapEntries([ "ID", "Label", "KeyCode", "File", "AnalysisValue", "Fixed", "Exclusive" ], s => s.toLowerCase()));

export function isAvailableDatabaseQuestionsColumnProperty(str: string): boolean {
    return textToMetadataDatabaseQuestionsColumnProperty.get(normalizeLineFeedCharacter(str.toLowerCase())) !== undefined;
}

export function metadataFieldFlagToString(flag: MDMFieldFlags) {
    switch (flag) {
        case MDMFieldFlags.long:                 return "long";
        case MDMFieldFlags.double:               return "double";
        case MDMFieldFlags.text:                 return "text";
        case MDMFieldFlags.date:                 return "date";
        case MDMFieldFlags.boolean:              return "boolean";
        case MDMFieldFlags.categorical:          return "categorical";
        case MDMFieldFlags.define:               return "define";
        case MDMFieldFlags.info:                 return "info";
        case MDMFieldFlags.categoricalLoop:      return "categorical loop";
        case MDMFieldFlags.numericLoop:          return "numeric loop";
        case MDMFieldFlags.grid:                 return "grid";
        case MDMFieldFlags.compound:             return "compound";
        case MDMFieldFlags.block:                return "block";
        case MDMFieldFlags.page:                 return "page";
        case MDMFieldFlags.databaseQuestions:    return "db";
    }
    return "unknown";
}

export function symbolFlagToString(flag: SymbolKind): string {
    switch (flag & (~SymbolKind.undefined)) {
        case SymbolKind.variable:    return "变量";
        case SymbolKind.array:       return "数组";
        case SymbolKind.constant:    return "常量";
        case SymbolKind.enum:        return "枚举";
        case SymbolKind.function:    return "函数";
        case SymbolKind.interface:   return "接口";
        case SymbolKind.class:       return "类";
        case SymbolKind.method:      return "方法";
        case SymbolKind.property:    return "属性";
    }
    return "unknown";
}

